﻿using System;
using System.IdentityModel.Tokens.Jwt;
using Abp.AspNetCore;
using Abp.Castle.Logging.Log4Net;
using Abp.EntityFrameworkCore;
using Abp.IdentityServer4;
using Alipay.AopSdk.AspnetCore;
using Alipay.AopSdk.F2FPay.AspnetCore;
using AVISOutBound.SSOServer.Authorization.Members;
using AVISOutBound.SSOServer.Configuration;
using AVISOutBound.SSOServer.EntityFrameworkCore;
using Castle.Facilities.Logging;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Swashbuckle.AspNetCore.Swagger;
using Microsoft.EntityFrameworkCore;
using AVISOutBound.SSOServer.Web.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Configuration;
using AVISOutBound.SSOServer.Identity;
using System.Reflection;
using AVISOutBound.SSOServer.Payment.Wechat;
using IdentityServer4.Services;
using IdentityServer4.Validation;
using Microsoft.IdentityModel.Tokens;

namespace AVISOutBound.SSOServer.Web.Startup
{
    public class Startup
    {
        private const string DefaultCorsPolicyName = "AllowSameDomain";

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public IServiceProvider ConfigureServices(IServiceCollection services)
        {

            // Configure DbContext
            //services.AddDbContext<SSOServerDbContext>(options =>
            //{
            //    options.UseSqlServer(Configuration.GetConnectionString(SSOServerConsts.ConnectionStringName));
            //});
            //services.AddTransient<SSOServerDbContext>(provider =>
            //    {
            //        return provider.GetRequiredService<IDbContextProvider<SSOServerDbContext>>().GetDbContext();
            //    });
            services.AddAbpDbContext<SSOServerDbContext>(options =>
            {
                DbContextOptionsConfigurer.Configure(options.DbContextOptions, options.ConnectionString);
            });
			
			// lulus:数据初始化相关服务
            services.AddTransient<DataSeeder>();

            services.AddMvc(options =>
            {
                //options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
            });
            
            // 启用ASP.NET Core Identity
            IdentityRegistrar.Register(services);

            // 添加IdentityServer相关的注入项
            services.AddIdentityServer(options =>
                {
                    options.Authentication.CookieLifetime = new TimeSpan(0, 0, 10);
                    options.Authentication.CookieSlidingExpiration = false;
                })
                .AddJwtBearerClientAuthentication()
                .AddDeveloperSigningCredential()
                // lulus:此处添加正式证书,不知道证书加密类型,未作处理
                //.AddSigningCredential()
                .AddConfigurationStore<SSOServerDbContext>()
                .AddProfileService<DefaultProfileService>()
                .AddConfigurationStoreCache()
            // lulus:不做单点授权
            //.AddAbpPersistedGrants<SSOServerDbContext>()
            // linfei 重写了AddAbpIdentityServer这个扩展方法，去除了AbpUser的依赖
            //.AddAbpIdentityServer<Member>();
            .AddABGIdentityServer<Member>();

            // 启用 Swagger
            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new Info { Title = "ABG单点登录服务", Version = "v1" });
                options.DocInclusionPredicate((docName, description) => true);

                // Define the BearerAuth scheme that's in use
                //options.AddSecurityDefinition("bearerAuth", new ApiKeyScheme()
                //{
                //    Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                //    Name = "Authorization",
                //    In = "header",
                //    Type = "apiKey"
                //});
                // Assign scope requirements to operations based on AuthorizeAttribute
                //options.OperationFilter<SecurityRequirementsOperationFilter>();
            });
            services.AddAlipay(options =>
            {
                //options.AlipayPublicKey = Configuration["Alipay:AlipayPublicKey"];
                //options.AppId = Configuration["Alipay:AppId"];
                //options.CharSet = Configuration["Alipay:CharSet"];
                //options.Gatewayurl = Configuration["Alipay:Gatewayurl"];
                //options.PrivateKey = Configuration["Alipay:PrivateKey"];
                //options.SignType = Configuration["Alipay:SignType"];
                //options.Uid = Configuration["Alipay:Uid"];

                //options.AlipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEApTbgfFd59D933Z3blXv5q14D71h0Uz1r4pZumW2WJBdh//8axTQUTvf0yEGkefX4pdRnHVxDx0syPxc6fk5tJ+YCD0uz9mM7jhLnDwE6z+1Njutn4A3hEdPVFrmtWuSqFzyUADfMrUG5ZfOCUEr81Oui/9LJNIMwDtU3zE2gjfRMEf8RLe9xwO1/Sn48l/SW2cj5Tkc/T/GMZIRf/bOQzBd/kecFh5mYKp5uduei4JKVBFJ7jt2gTSb2riC3p21VF97XUQFnMAwOhvxcbcyobXX/WicPKwgB9HqMB81+lFxk1GYOydZ8Ea8PKqww1s1TzorhoxXvTHa1NZuuoHTQjQIDAQAB";
                //options.AppId = "2018041902582051";
                //options.CharSet = "UTF-8";
                //options.Gatewayurl = "https://openapi.alipay.com/gateway.do";
                //options.PrivateKey = "MIIEpAIBAAKCAQEA3RGrkkrDORf2jNSWr4rvucx3wpQ7T3RsW9R7MoMGh79+Rw4qU2OOqkBd4y91ChkY7c1f4FJTvau5DeXlfYgf67LAjQbFbMZLqfwxyOlmj1leqoYAUn3g3Ve5sjMx2vgokB7wSMm1rzPbla5aTMY7cUpQMw5bQMFETXbw5o2DI8rOFHch6ZqBWFvwSjQtKg8lRoQRLRjVGkMn0RMIBRCrlX5U1BP+vaIg25JMO/9fh6F9RbayfP4CJGrislknCea65rRWkztEdgKVVlBedVz8ajWwtw2+QbFIp6ze7/TgsAJIXqM2dwSBF2jDuH0lkUdwJJlTi+rDi2bWRjwlwKN/cwIDAQABAoIBAFjKChD9uh8qQroZgFQNB2+mcctS4edtqT/QvZJyEaNgBAXh6JoJeHlk1NC0dNuTbPHF9OYR6tRZLkAov92FWNy/tJpvx8eCdU1Wn2BEbg7RJDZ1D5gSOshrvYeXDEUYOqJ36qYxbalquJ0Lo/UGAUXlRQTclUYS2a4LQYI4AB3VTYfxRgmtXxiYakdYCP5P/dLuDvdvlC4kxpLbiizIJKkjClPXGBq0g0zkes5rb6N/cgyfzasq95PF0UeHRY+t02iVdPEclXWQwss8gm7jP9A4q6YeQCsjGUSjXhhqsejdprPDxm7FxrZLa66kiFM3YLO9PRgGT6KaKPWClXThaRECgYEA8KWxz3u/KadxVqnQabrzSd91kYfxnOJAFZGB/sb7vAoiRhGAFw13vkvhtteUADLpN5uuqCY8HZFYSBjPRlZOy1aa1U2m9Zn19aRDJEEWleV4Skj0ZyR3gvnrU3XvbL+88QJXRHlz2SH1bttVrdAEaVIWx7eArB1RUUPFdsgu1C8CgYEA6yw4Pbk8nIyk76Sbi/mD9awmMQIMPoYUpfw+fmUtD5Z9HF4T9EZw72orjuz3SSqsvemAts4a5TCTnWg5UaCOeMnhoCyvprNf0GHmMQxnF2ovGEk9UpaDKI2E1HDkEjMSPyE31KILTV91m4e9rn5fDpKS4JYx9UOzkQinUnIEw/0CgYAsn/1WJXNwjP1mfb0JLkLZSxfpMdVrK0WI+l+p2EpsN1Ddv3cKT1QKNNYZauamFsrKphMAWX7CWOaPEBK3z19zM48oyOqSFsfWkmxk97DxgQkKdXbk/Y0v+5pY8sDAYNnvs2htaTxDYpm5wfCkd7OpuDBDPtMcl58xu6iNe1e7vwKBgQC7RW9T15pon6cIHnCvOnbWv8t540OU1njC5OdvB2qmqxPd7xy8vQtZ25XsLs+MuCru4G7bI61PLSufgUuDsPNDRKAjSPJnMRfvfMYt8M53Wts937Sxe6HePTO1aGB2Da1OEEnBTXjqmEWzIJjvxzozBI1pwrDtuofXyqhTgvBAkQKBgQDfvaI2qIXDLEowmk1i2v4bmdOqZyQpJ6Re2uzL91U43o8i4qH14O+1DnM634CgSVr9wP3acdyqPaewIkxkM+NR8fIQ63AnbcKQ+AMgBxCjG+TJpZI4vpHuzE3slhPssMQWjCzrxnYjlmli+I2EJSbz9OmSiy3RtsjrmPcMwmOfsg==";
                //options.SignType = "RSA2";
                //options.Uid = "2088031973435294";
            }).AddAlipayF2F();

            //AlipayConfigChecker.Check(Configuration["Alipay:SignType"], Configuration["Alipay:PrivateKey"]);
            //AlipayConfigChecker.Check("RSA2", "MIIEpAIBAAKCAQEA3RGrkkrDORf2jNSWr4rvucx3wpQ7T3RsW9R7MoMGh79+Rw4qU2OOqkBd4y91ChkY7c1f4FJTvau5DeXlfYgf67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y0v+5pY8sDAYNnvs2htaTxDYpm5wfCkd7OpuDBDPtMcl58xu6iNe1e7vwKBgQC7RW9T15pon6cIHnCvOnbWv8t540OU1njC5OdvB2qmqxPd7xy8vQtZ25XsLs+MuCru4G7bI61PLSufgUuDsPNDRKAjSPJnMRfvfMYt8M53Wts937Sxe6HePTO1aGB2Da1OEEnBTXjqmEWzIJjvxzozBI1pwrDtuofXyqhTgvBAkQKBgQDfvaI2qIXDLEowmk1i2v4bmdOqZyQpJ6Re2uzL91U43o8i4qH14O+1DnM634CgSVr9wP3acdyqPaewIkxkM+NR8fIQ63AnbcKQ+AMgBxCjG+TJpZI4vpHuzE3slhPssMQWjCzrxnYjlmli+I2EJSbz9OmSiy3RtsjrmPcMwmOfsg==");

            // 添加跨域处理
            services.AddCors(options =>
            {
                options.AddPolicy(DefaultCorsPolicyName, builder =>
                {
                    builder
                        //.WithOrigins(_appConfiguration["App:CorsOrigins"].Split(",", StringSplitOptions.RemoveEmptyEntries).Select(o => o.RemovePostFix("/")).ToArray())
                        .AllowAnyOrigin() //TODO: Will be replaced by above when Microsoft releases microsoft.aspnetcore.cors 2.0 - [图片]https://github.com/aspnet/CORS/pull/94
                        .AllowAnyHeader()
                        .AllowAnyMethod();
                });
            });

            //Configure Abp and Dependency Injection
            return services.AddAbp<SSOServerWebModule>(options =>
            {
                //Configure Log4Net logging
                options.IocManager.IocContainer.AddFacility<LoggingFacility>(
                    f => f.UseAbpLog4Net().WithConfig("log4net.config")
                );
            });
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            app.UseAbp(); //Initializes ABP framework.

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
            }

            app.UseStaticFiles();
            app.UseIdentityServer();

            app.UseAuthentication();

            app.UseCors(DefaultCorsPolicyName);// Enable CORS

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

            // 使中间件能够将生成的Swagger作为JSON端点
            // Enable middleware to serve generated Swagger as a JSON endpoint
            app.UseSwagger();

            // 采用中间件服务的swagger-ui资源（HTML，JS，CSS等）
            // Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.)
            app.UseSwaggerUI(options =>
            {
                //options.InjectOnCompleteJavaScript("/swagger/ui/abp.js");
                //options.InjectOnCompleteJavaScript("/swagger/ui/on-complete.js");
                options.SwaggerEndpoint("/swagger/v1/swagger.json", "ABG单点登录服务 API V1");
                //options.IndexStream = () => Assembly.GetExecutingAssembly()
                //    .GetManifestResourceStream("AVISOutBound.SSOServer.Web.wwwroot.swagger.ui.index.html");
            }); // URL: /swagger
        }
    }
}
